package com.www.applyword.main;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IMEventListener;
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import com.www.applyword.R;
import com.www.applyword.base.BaseApplication;
import com.www.applyword.fragment.ChatFragment;
import com.www.applyword.fragment.ChoicenessFragment;
import com.www.applyword.fragment.HomeFragment;
import com.www.applyword.fragment.MessageFragment;
import com.www.applyword.fragment.MyFragment;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * @author Administrator
 */
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, AMapLocationListener, ConversationManagerKit.MessageUnreadWatcher {
    @BindView(R.id.rb_main_home)
    RadioButton rbMainHome;
    @BindView(R.id.rb_main_chat)
    RadioButton rbMainChat;
    @BindView(R.id.rb_main_my)
    RadioButton rbMainMy;

    private BaseApplication mApplication;
    private RadioGroup mRg_content_fragment;
    private ArrayList<Fragment> mFragments;
    private HomeFragment homeFragment = new HomeFragment();
    private ChoicenessFragment chatFragment = new ChoicenessFragment();
    private MyFragment myFragment = new MyFragment();

    public static MainActivity mContext;

    private Fragment mContent;

    public static final String MSG = "msg";

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public double latitude;
    public double longitude; //经度
    public String city;
    private Fragment currentFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = MainActivity.this;
        //   mApplication = (BaseApplication) getApplication();
        //  mApplication.addActvity(this);
        initFragments();
        initView();
        //添加点击事件
        initListener();
        //定位
        getLocationInfo();
        TUIKit.addIMEventListener(mIMEventListener);

        //获取会话扩展实例
       /* TIMConversation con = TIMManager.getInstance().getConversation(TIMConversationType.C2C, SPUtil.getString(Constants.USERID));
       //获取会话未读数
        long num = con.getUnreadMessageNum();
        if (num > 0){
            unread_msg_number.setVisibility(View.VISIBLE);
            unread_msg_number.setText(num + "");
        }else {
            unread_msg_number.setVisibility(View.INVISIBLE);
        }*/
    }


    // 监听做成静态可以让每个子类重写时都注册相同的一份。
    private  IMEventListener mIMEventListener = new IMEventListener() {
        @Override
        public void onForceOffline() {
            Utils.showToastSafe("您的帐号已在其它终端登录");
            SPUtil.put("login", false);
            TUIKit.unInit();
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        }
    };


    private void initView() {
        mRg_content_fragment = (RadioGroup) findViewById(R.id.rg_content_fragment);
        mRg_content_fragment.setOnCheckedChangeListener(this);
       // changeFragment(0);
        replaceFragment("home");
        //  mRg_content_fragment.check(R.id.rb_main_home);
        Bitmap a = null;
      //  rbMainHome.setButtonDrawable(new BitmapDrawable(a));
      //  rbMainChat.setButtonDrawable(new BitmapDrawable(a));
       // rbMainMy.setButtonDrawable(new BitmapDrawable(a));

        HashMap<String, Object> hashMap = new HashMap<>();
        // 地区
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_LOCATION, "sz"); // TODO 不加SDK会有个崩溃
        hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_ALLOWTYPE, "AllowType_Type_NeedConfirm");  //加好友验证方式
        TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
            }

            @Override
            public void onSuccess() {
                // Utils.showToastSafe("设置成功");
                //  DemoLog.i(TAG, "modifySelfProfile success");
            }
        });
    }


    private void initFragments() {
        mFragments = new ArrayList<>();
        mFragments.add(homeFragment);
        mFragments.add(chatFragment);
        mFragments.add(myFragment);
    }

    private void changeFragment(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fl_container, mFragments.get(position));
        transaction.commit();
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int position = group.indexOfChild(group.findViewById(checkedId));
        // Fragment baseFragment = getFragment(position);
        //  switchFragment(mContent, baseFragment);
        switch (position){
            case 0:
                replaceFragment("home");
                break;
            case 1:
                replaceFragment("circle");
                break;
            case 2:
                replaceFragment("mine");
                break;
            default:
        }
    }

    private Fragment getFragment(int position) {
        if (mFragments != null && mFragments.size() > 0) {
            Fragment baseFragment = mFragments.get(position);
            return baseFragment;
        }
        return null;
    }

    private void switchFragment(Fragment fromFragment, Fragment nextFragment) {
        if (mContent != nextFragment) {
            mContent = nextFragment;
            if (nextFragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判断nextFrragment是否添加
                if (!nextFragment.isAdded()) {
                    //隐藏当前Fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.add(R.id.fl_container, nextFragment).commit();
                } else {
                    //隐藏当前fragment
                    if (fromFragment != null) {
                        transaction.hide(fromFragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }


    private void replaceFragment(String tag) {
        if (currentFragment != null) {
            Log.i("MainActivity", tag + "-----1");
            getSupportFragmentManager().beginTransaction().hide(currentFragment).commit();
        }
        currentFragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (currentFragment == null) {
            switch (tag) {
                case "home":
                    currentFragment = new HomeFragment();
                    break;
                case "circle":
                    currentFragment = new ChoicenessFragment();
                    break;
                case "mine":
                    currentFragment = new MyFragment();
                    break;
                default:
            }
            Log.i("MainActivity", tag + "-----2");
            getSupportFragmentManager().beginTransaction().add(R.id.fl_container, currentFragment, tag).commit();
        } else {
            getSupportFragmentManager().beginTransaction().show(currentFragment).commit();
        }
    }


    private void initListener() {
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.READ_PHONE_STATE
                        , Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                .subscribe(granted -> {
                    if (granted) {
                        //  Toast.makeText(MainActivity.this, "同意权限", Toast.LENGTH_SHORT).show();
                    } else {
                        //  Toast.makeText(MainActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    private void getLocationInfo() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(MainActivity.this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        //  mLocationOption.setInterval(2000);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        //启动定位
        mlocationClient.startLocation();

        // 未读消息监视器
        ConversationManagerKit.getInstance().addUnreadWatcher(this);
        GroupChatManagerKit.getInstance();

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                city = aMapLocation.getCity();
                SPUtil.put("latitude", latitude);
                SPUtil.put("longitude", longitude);
                SPUtil.put("address", aMapLocation.getAddress());
                SPUtil.put("city", city);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public void updateUnread(int count) {

    }
}
